package weaver.batchchanges.schedule;

import com.engine.common.util.ServiceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.batchchanges.bean.BatchTasksChangesGlobalData;
import weaver.batchchanges.bean.BatchTasksChangesRequestData;
import weaver.batchchanges.bean.TaskHasChangedBean;
import weaver.batchchanges.service.BatchTasksChangesService;
import weaver.batchchanges.service.impl.BatchTasksChangesServiceImpl;
import weaver.batchchanges.util.DataConvertUtil;
import weaver.batchchanges.util.OkHttpUtils;
import weaver.batchchanges.util.SameOriginRequestsUtil;
import weaver.interfaces.schedule.BaseCronJob;

import java.util.List;


/**
 * 批量任务变更定时任务
 */
public class BatchTasksChangesCron extends BaseCronJob {
    private final Logger logger = LoggerFactory.getLogger(BatchTasksChangesCron.class);

    //批量变更接口url地址 （通过定时任务参数自动注入值）
    private final String BATCH_TASKS_CHANGES_URL = "BatchTasksChanges";
    private final String DEFAULT_SCHEME = "http";
    private final String DEFAULT_HOST = "127.0.0.1:9080";

    @Override
    public void execute() {
        logger.info("---BatchTasksChangesCron start!!!---");
        try {
            //获取service实例
            BatchTasksChangesService batchTasksChangesService = ServiceUtil.getService(BatchTasksChangesServiceImpl.class);

            //获取需要任务变动的数据
            List<TaskHasChangedBean> allTaskHasChanged = batchTasksChangesService.getAllTaskHasChanged();
            //创建请求参数的对象
            BatchTasksChangesRequestData batchTasksChangesRequestData = BatchTasksChangesRequestData.builder(allTaskHasChanged);
            logger.info("Parameters of the request created:::\n" + batchTasksChangesRequestData);
            //发起更改请求
            SameOriginRequestsUtil.getInstance(DEFAULT_SCHEME, DEFAULT_HOST)
                    .post(BATCH_TASKS_CHANGES_URL,
                            DataConvertUtil.convertToMap(batchTasksChangesRequestData),
                            OkHttpUtils.MediaTypeEnum.JSON);
        } catch (Exception e) {
            logger.error("An unknown anomaly occurred :::\n" + e.getMessage(), e);
        }

        logger.info("---BatchTasksChangesCron end!!!---");

    }
}
